package com.ruoyi.kindergarten.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.kindergarten.domain.ClassInfo;
import com.ruoyi.kindergarten.domain.Student;
import com.ruoyi.kindergarten.mapper.ClassInfoMapper;
import com.ruoyi.kindergarten.mapper.StudentMapper;
import com.ruoyi.kindergarten.service.MqttCommandService;
import com.ruoyi.kindergarten.util.HttpClientUtil;
import com.ruoyi.kindergarten.util.MinioUtil;
import com.ruoyi.kindergarten.websocket.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.kindergarten.mapper.BehaviorMonitorMapper;
import com.ruoyi.kindergarten.domain.BehaviorMonitor;
import com.ruoyi.kindergarten.service.IBehaviorMonitorService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 行为检测与报警模块Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-26
 */
@Service
public class BehaviorMonitorServiceImpl implements IBehaviorMonitorService 
{
    @Autowired
    private BehaviorMonitorMapper behaviorMonitorMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Autowired
    private WebSocketService webSocketService;

    @Resource
    private MqttCommandService mqttCommandService;

    @Autowired
    private MinioUtil minioUtil;

    private static final String TARGET_COMMAND = "0105000100009C0A";


    private static final String TARGET_COMMANDxx = "01050001FF00DDFA";

    private static final String URL = "http://10.196.101.27:1662/thing/provider/rest/monitor/alarms/2306328859501170";
    /**
     * 查询行为检测与报警模块
     * 
     * @param id 行为检测与报警模块主键
     * @return 行为检测与报警模块
     */
    @Override
    public BehaviorMonitor selectBehaviorMonitorById(Long id)
    {
        BehaviorMonitor behaviorMonitor = behaviorMonitorMapper.selectBehaviorMonitorById(id);
        Student student = studentMapper.selectStudentById(behaviorMonitor.getStudentId());
        if (student != null) {
            behaviorMonitor.setStudentName(student.getName());

        }
        ClassInfo classInfo = classInfoMapper.selectClassInfoById(behaviorMonitor.getClassId());
        if (classInfo != null) {
            behaviorMonitor.setClassName(classInfo.getClassName());
        }

        return behaviorMonitor;
    }

    /**
     * 查询行为检测与报警模块列表
     * 
     * @param behaviorMonitor 行为检测与报警模块
     * @return 行为检测与报警模块
     */
    @Override
    public List<BehaviorMonitor> selectBehaviorMonitorList(BehaviorMonitor behaviorMonitor)
    {
        List<BehaviorMonitor> behaviorMonitorList = behaviorMonitorMapper.selectBehaviorMonitorList(behaviorMonitor);
        behaviorMonitorList.forEach(item->{
            Student student = studentMapper.selectStudentById(item.getStudentId());
            if (student != null) {
                item.setStudentName(student.getName());

            }
            ClassInfo classInfo = classInfoMapper.selectClassInfoById(item.getClassId());
            if (classInfo != null) {
                item.setClassName(classInfo.getClassName());
            }
        });

        return behaviorMonitorList;
    }

    /**
     * 新增行为检测与报警模块
     * 
     * @param behaviorMonitor 行为检测与报警模块
     * @return 结果
     */
    @Override
    public int insertBehaviorMonitor(BehaviorMonitor behaviorMonitor, MultipartFile file) throws Exception {
        String imgURL = minioUtil.uploadFile(file, file.getName());
        if (behaviorMonitor.getBehaviorName().equals("荡秋千危险行为")){
            behaviorMonitor.setStudentId(1L);
            behaviorMonitor.setClassId(1L);
            behaviorMonitor.setLocation("乐园");
            behaviorMonitor.setAlertStatus(0L);
            behaviorMonitor.setAlertTime(new Date());
        }else if (behaviorMonitor.getBehaviorName().equals("孩子爬东西可能有危险")){
            behaviorMonitor.setStudentId(1L);
            behaviorMonitor.setClassId(1L);
            behaviorMonitor.setLocation("二班教室");
            behaviorMonitor.setAlertStatus(0L);
            behaviorMonitor.setAlertTime(new Date());
        }
        behaviorMonitor.setImg(imgURL);
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonMessage = objectMapper.writeValueAsString(behaviorMonitor);
        webSocketService.onMessage(jsonMessage);
        return behaviorMonitorMapper.insertBehaviorMonitor(behaviorMonitor);
    }

    /**
     * 修改行为检测与报警模块
     * 
     * @param behaviorMonitor 行为检测与报警模块
     * @return 结果
     */
    @Override
    public int updateBehaviorMonitor(BehaviorMonitor behaviorMonitor)
    {
        boolean b = mqttCommandService.sendHexCommand(TARGET_COMMAND);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            HttpClientUtil.doPost4JsonArray(URL, Fz(behaviorMonitor), null);
            String str = objectMapper.writeValueAsString(behaviorMonitor);
            webSocketService.onMessage(str);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (!b){
            throw new RuntimeException("mqtt协议处理");
        }
        return behaviorMonitorMapper.updateBehaviorMonitor(behaviorMonitor);
    }
    private List<Map<String,String>> Fz(BehaviorMonitor behaviorMonitor){
        List<Map<String,String>> list = new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if(behaviorMonitor.getLocation().equals("乐园")){
            map.put("twinID","摄像头4");
            map.put("severity","1");
            map.put("status","2");
            map.put("sourceAlertKey","荡秋千危险行为");
            map.put("summary","荡秋千危险行为");
            map.put("sourceIdentifier","xxx");
            map.put("lastOccurrence",formatter.format(now));
            list.add(map);
        }else {
            map.put("twinID","摄像头112");
            map.put("severity","1");
            map.put("status","2");
            map.put("sourceAlertKey","孩子爬东西可能有危险");
            map.put("summary","孩子爬东西可能有危险");
            map.put("sourceIdentifier","xx");
            map.put("lastOccurrence",formatter.format(now));
            list.add(map);
        }
        return list;
    }

    /**
     * 批量删除行为检测与报警模块
     * 
     * @param ids 需要删除的行为检测与报警模块主键
     * @return 结果
     */
    @Override
    public int deleteBehaviorMonitorByIds(Long[] ids)
    {
        return behaviorMonitorMapper.deleteBehaviorMonitorByIds(ids);
    }

    /**
     * 删除行为检测与报警模块信息
     * 
     * @param id 行为检测与报警模块主键
     * @return 结果
     */
    @Override
    public int deleteBehaviorMonitorById(Long id)
    {
        return behaviorMonitorMapper.deleteBehaviorMonitorById(id);
    }
}
